package com.yunjian.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        String[] fields = binder.getAllowedFields();
        logger.info(binder.getAllowedFields().toString());
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "chengfangjian");
    }


    /**
     * 系统异常处理，比如：404,500
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public String defaultErrorHandler(HttpServletRequest req, Exception e, Model map) throws Exception {
        map.addAttribute("msg", e.getMessage());
        map.addAttribute("url", req.getRequestURL());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            return "404";
        } else {
            return "500";
        }
    }
}
